import { ElMessage, ElMessageBox, FormItemRule } from 'element-plus'
import { CSSProperties, VNode } from 'vue'
import { commonFontSize } from './layoutUtil'
import { formatDate, getLastDate } from '@/utils/dateUtil'

/**
 * 输入框规则 中英文、数字
 */
export const inputPattern = /^[\u4e00-\u9fa5a-zA-Z0-9]+$/

/**
 * 英文、数字
 */
export const noChineseInputPattern = /^[0-9a-zA-Z]+$/

/**
 * 中英文
 */
export const noNumberInputPattern = /^[\u4e00-\u9fa5a-zA-Z]+$/

/**
 * 手机号
 */
export const phoneNumberPattern = /^1[3-9]\d{9}$/

/**
 * 身份证校验，使用：{ validator: validatorIdCard, trigger: 'blur' }
 * @param rule
 * @param value
 * @param callback
 */
export const validatorIdCard = (rule: FormItemRule, value: any, callback: Function) => {
  if (!value) {
    callback()
    return
  }

  // 验证长度
  if (!/^\d{17}(\d|x)$/i.test(value)) {
    callback(new Error('身份证格式错误'))
    return
  }

  // 地区编号
  const cityCodeList = [
    11, 12, 13, 14, 15,
    21, 22, 23,
    31, 32, 33, 34, 35, 36, 37,
    41, 42, 43, 44, 45, 46,
    50, 51, 52, 53, 54,
    61, 62, 63, 64, 65,
    71, 81, 82, 91
  ]

  // 验证前两位是否为省份代码
  const cityNum = parseInt(value.replace(/x$/i, 'a').substring(0, 2), 10)
  if (!cityCodeList.includes(cityNum)) {
    callback(new Error('身份证地区格式错误'))
    return
  }

  // 身份证上的出生年月校验
  const birthYear = value.substring(6, 10)
  const birthMonth = value.substring(10, 12)
  const birthDay = value.substring(12, 14)
  const birth = `${birthYear}-${birthMonth}-${birthDay}`
  if (!Date.parse(birth)) {
    callback(new Error('身份证生日格式格式错误'))
    return
  }

  // 身份证校验位判断
  let iSum = 0
  for (let i = 17; i >= 0; i--) {
    iSum += (Math.pow(2, i) % 11) * parseInt(value.charAt(17 - i), 11)
  }
  if (iSum % 11 !== 1) {
    callback(new Error('身份证校验码错误'))
    return
  }

  callback()
}

/**
 * 自定义合并单元格
 * @param dataList 数据
 * @param rowKey 需要合并的字段
 * @param rowIndex 行所有
 * @param row 行数据
 */
export const getRowspan = (dataList: any[], rowKey: string, rowIndex: number, row: any) => {
  // 获取当前单元格的值
  const currentValue = row[rowKey]
  // 获取上一行相同列的值
  const preRow = dataList[rowIndex - 1]
  const preValue = preRow ? preRow[rowKey] : null
  // 如果当前值和上一行的值相同，则将当前单元格隐藏
  if (currentValue === preValue) {
    return {
      rowspan: 0,
      colspan: 0
    }
  } else {
    // 否则计算当前单元格应该跨越多少行
    let rowspan = 1
    for (let i = rowIndex + 1; i < dataList.length; i++) {
      const nextRow = dataList[i]
      const nextValue = nextRow[rowKey]
      if (nextValue === currentValue) {
        rowspan++
      } else {
        break
      }
    }
    return {
      rowspan,
      colspan: 1
    }
  }
}

/**
 * 自定义统计数据
 * @param columns 列
 * @param data 数据
 * @param summaryColumnList 需要统计的列
 */
export const getSummaryData = (columns: any[], data: any[], summaryColumnList: string[]) => {
  const sums: Array<string | VNode> = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (summaryColumnList.includes(column.property)) {
      const values = data.map((item) => Number(item[column.property]))
      const summaryValue = values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!Number.isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)
      sums[index] = summaryValue.toString()
    } else {
      sums[index] = ''
    }
  })

  return sums
}

/**
 * 表格样式属性
 */
const elTableStyle = {
  height: '5vh',
  headerBgColor: '#F4F1EE',
  color: '#000000',
  borderWidth: '2px'
}

/**
 * 表头样式
 */
export const tableHeaderStyle = (background = elTableStyle.headerBgColor,
  height = elTableStyle.height, color = elTableStyle.color, fontSize = commonFontSize,
  borderWidth = elTableStyle.borderWidth): CSSProperties => {
  return { height, background, color, fontSize, borderWidth }
}

/**
 * 单元格样式
 */
export const tableCellStyle = (fontSize = commonFontSize,
  borderWidth = elTableStyle.borderWidth): CSSProperties => {
  return { fontSize, borderWidth }
}

/**
 * 表格行样式
 */
export const tableRowStyle = (height = elTableStyle.height): CSSProperties => {
  return { height }
}

/**
 * 日期选择
 */
export const elDateShortcuts = [
  {
    text: '近7天',
    value: () => {
      return [getLastDate(new Date(), 7, 'days'), formatDate(new Date())]
    }
  },
  {
    text: '近30天',
    value: () => {
      return [getLastDate(new Date(), 30, 'days'), formatDate(new Date())]
    }
  },
  {
    text: '近90天',
    value: () => {
      return [getLastDate(new Date(), 90, 'days'), formatDate(new Date())]
    }
  },
  {
    text: '近半年',
    value: () => {
      return [getLastDate(new Date(), 0.5, 'years'), formatDate(new Date())]
    }
  },
  {
    text: '近一年',
    value: () => {
      return [getLastDate(new Date(), 1, 'years'), formatDate(new Date())]
    }
  }
]

/**
 * ElMessage错误码提示
 * @param message 错误消息
 * @constructor
 */
export const ElMessageErrorTip = (message: string) => {
  ElMessage({
    message,
    type: 'error',
    duration: 5 * 1000
  })
}

export const commonElMessageBox = (title: string) => {
  return ElMessageBox.confirm(
    title,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'error'
    }
  )
}
